package com.example.administrator.im.ui.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.example.administrator.im.MyApplication;
import com.example.administrator.im.R;
import com.example.administrator.im.adapter.DetailsAdapter;
import com.example.administrator.im.config.ImageConfig;
import com.example.administrator.im.data.DetailsData;
import com.example.administrator.im.db.FriendDBHelper;
import com.example.administrator.im.db.GroupDBHelper;
import com.example.administrator.im.interfacz.Detailsable;
import com.example.administrator.im.json.ResultJson;
import com.example.administrator.im.utils.DialogUtils;
import com.example.administrator.im.utils.DownloadImageUtils;
import com.example.administrator.im.utils.FileUtils;
import com.example.administrator.im.utils.HttpUtils;
import com.google.gson.Gson;

import org.litepal.LitePal;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * create:2018/10/2 16:26
 * author: 姚鸿杰
 **/
public class FriendDetailsActivity extends AppCompatActivity {

    private final String TAG = "FriendDetailsActivity";

    private TextView afd_nickname;

    private ImageView iv_head_img;

    private String username = "";
    private String nickname = "";

    private FriendDBHelper friend;

    private RecyclerView recycler_friend_details;
    private DetailsAdapter adapter;

    public static final String TITLE[] = {"账号", "昵称", "个性签名", "备注", "分组"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        setContentView(R.layout.activity_friend_details);

        Intent intent = getIntent();
        if (intent != null) {
            username = intent.getStringExtra("username");
            nickname = intent.getStringExtra("nickname");
        }

        initView();
    }

    private void initView() {
        afd_nickname = (TextView) findViewById(R.id.afd_nickname);

        iv_head_img = (ImageView) findViewById(R.id.friend_head_img);

        recycler_friend_details = (RecyclerView) findViewById(R.id.recycler_friend_details);

        //从数据库获取数据
        friend = LitePal.where("username = ?", username).findFirst(FriendDBHelper.class);
        if (friend != null) {

            afd_nickname.setText(friend.getNickname());

            int group_id = friend.getGroup_id();
            GroupDBHelper group = LitePal.find(GroupDBHelper.class, group_id);

            List<DetailsData> list = new ArrayList<>();
            list.add(new DetailsData(TITLE[0], friend.getUsername(), true));
            list.add(new DetailsData(TITLE[1], friend.getNickname(), false));
            list.add(new DetailsData(TITLE[2], friend.getSignature(), false));
            list.add(new DetailsData(TITLE[3], friend.getRemarks(), true));
            list.add(new DetailsData(TITLE[4], group.getName() == null ? "" : group.getName(), false));

            recycler_friend_details.setLayoutManager(new LinearLayoutManager(this));
            adapter = new DetailsAdapter(list, this);
            recycler_friend_details.addItemDecoration(new
                    com.example.administrator.im.adapter.DividerItemDecoration(this, LinearLayout.VERTICAL));
            recycler_friend_details.setAdapter(adapter);

            adapter.setOnClickListener(new Detailsable() {
                @Override
                public void onClick(View v, int i) {
                    switch (i) {
                        case 3:
                            setRemarks(i);
                            break;
                        case 4:
                            setGroup(i);
                            break;
                    }
                }
            });

            String url = HttpUtils.PORT + friend.getImg_path();
            if (TextUtils.equals(url, HttpUtils.PORT)) {
                return;
            }
//            RequestOptions options = new RequestOptions()
//                    .placeholder(R.mipmap.login_logo)
//                    .error(R.mipmap.login_logo)
//                    .diskCacheStrategy(DiskCacheStrategy.NONE).override(ImageConfig.getPersonalBig(), ImageConfig.getPersonalBig());
            // Glide.with(this).load(url).apply(options).into(iv_head_img);
            saveImage(url, FileUtils.getFilePath(username, FileUtils.FRIEND_PACK), ImageConfig.getPersonalBig());
        }
    }

    private void saveImage(String url, final File file, int size) {
        if (!file.exists()) {
//            DownloadImageUtils downloadImage = new DownloadImageUtils(url, MyApplication.getmContext(),
//                    size, size, file, new DownloadImageUtils.ImagedownLoadCallBack() {
//                @Override
//                public void onDownLoadSuccess(final File file) {
//                    setImageView(file);
//                }
//
//                @Override
//                public void onDownLoadFailed() {
//                }
//            });
//            new Thread(downloadImage).start();
        } else {
            setImageView(file);
        }
    }

    private void setImageView(final File file) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = BitmapFactory.decodeFile(file.getPath());
                RequestOptions options = new RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE).override(ImageConfig.getPersonalBig(), ImageConfig.getPersonalBig());
                Glide.with(FriendDetailsActivity.this).load(bitmap).apply(options).into(iv_head_img);
            }
        });
    }

    public void iv_return(View v) {
        finish();
    }

    public void send_msg(View v) {
        Intent intent = new Intent(this, ChatRoomActivity.class);
        intent.putExtra("username", username);
        intent.putExtra("nickname", nickname);
        startActivity(intent);
    }

    private EditText et_remarks;
    private Button dialog_yes;

    private View getDialogLayout(String title, String hint) {
        LayoutInflater inflater = this.getLayoutInflater();
        View view_custom = inflater.inflate(R.layout.dialog_add_group, null, false);
        et_remarks = view_custom.findViewById(R.id.dialog_et_name);
        TextView tv_title = view_custom.findViewById(R.id.dialog_tv_title);
        et_remarks.setHint(hint);
        tv_title.setText(title);
        dialog_yes = (Button) view_custom.findViewById(R.id.dialog_yes);
        return view_custom;
    }

    private AlertDialog getAlertDialog(String title, String hint) {
        View v = getDialogLayout(title, hint);
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setView(v);
        final AlertDialog alert = builder.create();
        alert.show();

        v.findViewById(R.id.dialog_no).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alert.dismiss();
            }
        });
        return alert;
    }

    //设置备注
    private void setRemarks(final int pos) {
        final AlertDialog alert = getAlertDialog("备注", "请输入备注");
        dialog_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alert.dismiss();

                final String remarks = et_remarks.getText().toString();

                //创建等待加载动画
                DialogUtils.setDialog(FriendDetailsActivity.this, R.layout.loading);
                DialogUtils.showDialog();

                HttpUtils.editingFriendRequest(username, HttpUtils.FRIEND_REMARKS, remarks, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e(TAG, e.getMessage());
                        DialogUtils.clearAlerDialog();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        //关闭等待加载
                        DialogUtils.clearAlerDialog();

                        String content = response.body().string();
                        Gson gson = new Gson();
                        ResultJson json = gson.fromJson(content, ResultJson.class);
                        if (json.getCode() == HttpUtils.SUCCESS) {

                            //修改本地数据库
                            friend.setRemarks(remarks);
                            friend.save();

                            //更新UI
                            Message msg = new Message();
                            msg.what = UPDATE_REMARKS;
                            msg.obj = remarks;
                            msg.arg1 = pos;
                            handler.sendMessage(msg);

                            nickname = remarks;
                            //更新friends数据
//                                    EMUtils.saveFriends();

                        } else if (json.getCode() == HttpUtils.SUCCESS_NO_CONTENT) {
                            Log.e(TAG, json.getData().toString());
                        }
                    }
                });
            }
        });
    }

    private void setGroup(final int pos) {
        // 创建数据
        final List<GroupDBHelper> groups = LitePal.order("position asc").find(GroupDBHelper.class);
        int size = groups.size();
        final String[] items = new String[size];
        for (int i = 0; i < size; i++)
            items[i] = groups.get(i).getName();


        // 创建对话框构建器
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        int group_id = friend.getGroup_id();
        int position = LitePal.find(GroupDBHelper.class, group_id).getPosition();

        // 设置参数
        builder.setIcon(R.mipmap.grounp).setTitle("选择分组").setSingleChoiceItems(items, position
                , new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(final DialogInterface dialog, final int which) {

                        //创建等待加载动画
                        DialogUtils.setDialog(FriendDetailsActivity.this, R.layout.loading);
                        DialogUtils.showDialog();
                        dialog.dismiss();

                        HttpUtils.editingFriendRequest(username, HttpUtils.FRIEND_GROUP, String.valueOf(which), new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {
                                Log.e(TAG, e.getMessage());
                                DialogUtils.clearAlerDialog();
                            }

                            @Override
                            public void onResponse(Call call, Response response) throws IOException {
                                //关闭加载
                                DialogUtils.clearAlerDialog();

                                String content = response.body().string();
                                Gson gson = new Gson();
                                ResultJson json = gson.fromJson(content, ResultJson.class);
                                if (json.getCode() == HttpUtils.SUCCESS) {

                                    //更新本地数据库
                                    int group_id = LitePal.where("position = ?",
                                            String.valueOf(which)).findFirst(GroupDBHelper.class).getId();
                                    friend.setGroup_id(group_id);
                                    friend.save();

                                    //更新ui
                                    Message msg = new Message();
                                    msg.what = UPDATE_GROUPS;
                                    msg.arg1 = pos;
                                    msg.obj = items[which];
                                    handler.sendMessage(msg);

                                } else if (json.getCode() == HttpUtils.SUCCESS_NO_CONTENT) {
                                    Log.e(TAG, json.getData().toString());
                                }
                            }
                        });

                    }
                });
        builder.create().show();

    }


    private final int UPDATE_REMARKS = 1;
    private final int UPDATE_GROUPS = 2;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case UPDATE_REMARKS:
                    adapter.updateItem(msg.obj.toString(), msg.arg1);
                    break;
                case UPDATE_GROUPS:
                    adapter.updateItem(msg.obj.toString(), msg.arg1);
                    break;
                default:
                    Bitmap bitmap = (Bitmap) msg.obj;
                    iv_head_img.setImageBitmap(bitmap);
                    break;
            }
        }
    };

}
